// pages/writeOne/writeOne.js
Page({
  data: {
    id:null,
    date: '2025-06-04',
    typeRange: [
      { id: 0, name: '收入' },
      { id: 1, name: '支出' }
    ],
    typeIndex: 0,
    amount: '',
    remark: '',
    loginde: false
  },

  onLoad(options) {
    this.setData({
      id: options.id,
      date: this.getCurrentDate()
    })
    console.log("记一笔ID:"+options.id)
  },

  getCurrentDate() {
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
  },

  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },

  bindTypeChange(e) {
    this.setData({
      typeIndex: e.detail.value
    })
  },

  bindAmountInput(e) {
    this.setData({
      amount: e.detail.value
    })
  },

  bindRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  submit() {
    if(this.data.loginde){
      wx.showToast({title: '操作频繁', icon: 'none'})
      return
    }

    this.setData({
      loginde: true
    })

    if (!this.data.amount) {
      wx.showToast({
        title: '请输入金额',
        icon: 'none'
      })
      return
    }
    wx.cloud.callFunction({
      name: 'saveAccountDetail',
      data: {
        accountId: this.data.id,
        date: this.data.date,
        type: this.data.typeRange[this.data.typeIndex].id,
        amount: parseFloat(this.data.amount),
        remark: this.data.remark
      },
      success: res => {
        console.log(res)
        wx.showToast({
          title: '记账成功',
          icon: 'success',
          success: () => {
            // 清空表单
            this.setData({
              amount: '',
              remark: ''
            })
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2]; // 目标页面实例
            wx.navigateBack({
              delta: 1,
              success() {
                prevPage.onLoad(prevPage.options); // 重新加载数据
              }
            });
          }
        })
      },
      fail: err => {
        console.error('保存失败:', err)
        wx.showToast({title: '保存失败', icon: 'none'})
      }
    })
  }
})